package cn.xianshu.pay.service.impl;

import cn.xianshu.basic.exception.BasicException;
import cn.xianshu.basic.service.impl.BasicServiceImpl;
import cn.xianshu.pay.domain.PayAlipayInfo;
import cn.xianshu.pay.domain.PayBill;
import cn.xianshu.pay.domain.PayFlow;
import cn.xianshu.pay.service.IPayAlipayInfoService;
import cn.xianshu.pay.service.IPayBillService;
import cn.xianshu.pay.service.IPayService;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class PayServiceImpl extends BasicServiceImpl<PayFlow> implements IPayService {

    @Autowired
    private IPayAlipayInfoService payAlipayInfoService;

    @Autowired
    private IPayBillService payBillService;


    /**
     * 支付申请
     * @param orderNo
     * @return
     */
    @Override
    public String applyPay(String orderNo) {
        // 1.判断参数
        if (!StringUtils.hasLength(orderNo)){
            throw new BasicException("无效的请求");
        }
        // 2.加载支付宝配置
        PayAlipayInfo payAlipayInfo = payAlipayInfoService.selectFirst();
        if (payAlipayInfo == null){
            throw new BasicException("无效的支付宝配置，请联系管理员!");
        }
        // 3. 查询支付单
        PayBill payBill = payBillService.selectByNo(orderNo);
        if (payBill == null){
            throw new BasicException("无效的支付单!");
        }
        // 4.发起支付请求
        // 4.1设置参数（全局只需设置一次）
        Factory.setOptions(payAlipayInfo.getOptions());
        try {
            // 4.2 发起API调用，电脑网站
            String returnUrl = String.format(payAlipayInfo.getReturnUrl(), orderNo);

            AlipayTradePagePayResponse response = Factory.Payment.Page().pay(
                    payBill.getDigest(), // 标题
                    payBill.getUnionPaySn(), // 单号
                    payBill.getMoney().toString(), // 金额
                    returnUrl
            );

            // 3. 处理异常或响应
            System.out.println("=============================================================");
            System.out.println(response.body);
            System.out.println("=============================================================");
            if (ResponseChecker.success(response)){
                System.out.println("调用成功!");
                // 处理结果
                return response.body;
            } else {
                System.out.println("调用失败!");
            }

        } catch (Exception e) {
            System.out.println("调用遇到异常，原因:" + e.getMessage());
            throw  new RuntimeException(e.getMessage(), e);
        }
        return "支付申请失败!";
    }
}
